package message;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

import event.Direction;
import event.Missile;
import user.source.TankClient;

/**
 * 
 * @author 
 *
 */
public class MissileNewMsg implements Msg {
	Missile missile;
	int msgType = Msg.MISSILE_NEW_MSG;
	TankClient tc;
	
	public MissileNewMsg(Missile missile) {
		this.missile = missile;
	}

	public MissileNewMsg(TankClient tc) {
		this.tc = tc;
	}
	
	@Override
	public void send(DatagramSocket ds, String ip, int udpPort) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		DataOutputStream dos = new DataOutputStream(baos);
		try {
			//发送这个信息的类型是炮弹死亡的信息类型
			dos.writeInt(msgType);
			dos.writeInt(missile.tankId);
			dos.writeInt(missile.id);
			dos.writeInt(missile.x);
			dos.writeInt(missile.y);
			dos.writeInt(missile.dir.ordinal());
			dos.writeBoolean(missile.good);
		}catch(IOException e) {
			e.printStackTrace();
		}
		byte[] buffer = baos.toByteArray();
		
		try {
			DatagramPacket dp = new DatagramPacket(buffer,buffer.length,new InetSocketAddress(ip,udpPort));
			ds.send(dp);
		} catch(SocketException e){
			e.printStackTrace();
		} catch(IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void parse(DataInputStream dis) {
		try {
			int tankId = dis.readInt();
			if(tankId == tc.myTank.id) {
				return ;
			}
			int id = dis.readInt();
			int x = dis.readInt();
			int y = dis.readInt();
			Direction dir = Direction.values()[dis.readInt()];
			boolean good = dis.readBoolean();
			
			Missile missile = new Missile(tankId,x,y,good,dir,tc);
			missile.id = id;
			tc.missiles.add(missile);
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
